// pages/my/addmy/addmy.js

const app = getApp();
const util = require('../../../utils/util');
const common = require('../../../utils/common');
const api = require("../../../config/api");
const requestUtil = require("../../../utils/request");
const timConst = require("../../../config/const");
import QRCode from '../../../utils/weapp-qrcode.js'
Page({

    /**
     * 页面的初始数据
     */
    data: {
		image_url:api.url+"/profile/upload/2024/06/23/电子名片背景图_20240623113649A001.jpg",
		bcd_info:{
			bcAddress: "",
			bcBriefIntroduction: "",
			bcFile:[],
			bcId: '',
			bcImgList:[],
			bcMailbox: "",
			bcName: "",
			bcPosition: "",
			bcUserImg: "",
			bcUserName: "",
			bcUserPhone: "",
			bcWxImg: [],
			bcWxNumber: "",
			bcXCoordinate: "",
			bcYCoordinate: "",
			createBy: null,
			createTime: null,
			pcInsdate: "",
			pcProgramCode: "",
			pcSpeech: "",
			pcStatus: '',
			pcUptime: "",
			remark: null,
			updateBy: null,
			updateTime: null,
			userId: '',
			pcId:""
		},
		bcId:"",
		file_info:[],
		status:"insert"
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
		if(options.bcId){
			this.setData({
				status:"update"
			})
			this.setData({
				bcId:options.bcId
			})
		// 查询数据 放进去
		this.getbct_id()
		}else{
			let info=this.data.bcd_info
			info.userId=options.userId
			info.bcName=options.cpName
			info.bcUserPhone=options.userPhone
			info.pcId=options.cpId
			this.setData({
				bcd_info:info
			})
		}
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },
	// 方法函数
	updata(){
		if(this.data.bcd_info.bcAddress=="" && this.data.bcd_info.bcXCoordinate==""  && this.data.bcd_info.bcYCoordinate=="" ){
			wx.showModal({
				title:"未选择公司地址",
				confirmText:"去选择",
				success: (res) => {
					if(res.confirm){
						this.get_bcAddress()
					}
				}
			})
			return false;
		}
		let businessCard=this.data.bcd_info
		delete businessCard.updateTime
		delete businessCard.remark
		delete businessCard.updateBy
		delete businessCard.createTime
		delete businessCard.createBy
		wx.showLoading({
			title:"请稍后..."
		})
		if(this.data.status=="update"){
			requestUtil.request("POST","/bcd_api/update_bcd",{
				bcAddress:businessCard.bcAddress,
				bcBriefIntroduction:businessCard.bcBriefIntroduction,
				bcFile:JSON.stringify(businessCard.bcFile),
				bcId:businessCard.bcId,
				bcImgList:JSON.stringify(businessCard.bcImgList),
				bcMailbox:businessCard.bcMailbox,
				bcName:businessCard.bcName,
				bcPosition:businessCard.bcPosition,
				bcUserImg:JSON.stringify(businessCard.bcUserImg),
				bcUserName:businessCard.bcUserName,
				bcUserPhone:businessCard.bcUserPhone,
				bcWxImg:JSON.stringify(businessCard.bcWxImg),
				bcWxNumber:businessCard.bcWxNumber,
				bcXCoordinate:businessCard.bcXCoordinate,
				bcYCoordinate:businessCard.bcYCoordinate,
				pcId:businessCard.pcId,
				pcInsdate:businessCard.pcInsdate,
				pcProgramCode:businessCard.pcProgramCode,
				pcSpeech:businessCard.pcSpeech,
				pcStatus:businessCard.pcStatus,
				pcUptime:new Date(),
				userId:businessCard.userId,
				pcId:businessCard.pcId
			}).then((res)=>{
				console.log(res,"+++))))jjjjjjjjjjjj")
				wx.hideLoading()
			})
		}else if(this.data.status=="insert"){
			requestUtil.request("POST","/bcd_api/add_bcd",{
				bcAddress:businessCard.bcAddress,
				bcBriefIntroduction:businessCard.bcBriefIntroduction,
				bcFile:JSON.stringify(businessCard.bcFile),
				bcImgList:JSON.stringify(businessCard.bcImgList),
				bcMailbox:businessCard.bcMailbox,
				bcName:businessCard.bcName,
				bcPosition:businessCard.bcPosition,
				bcUserImg:JSON.stringify(businessCard.bcUserImg),
				bcUserName:businessCard.bcUserName,
				bcUserPhone:businessCard.bcUserPhone,
				bcWxImg:JSON.stringify(businessCard.bcWxImg),
				bcWxNumber:businessCard.bcWxNumber,
				bcXCoordinate:businessCard.bcXCoordinate,
				bcYCoordinate:businessCard.bcYCoordinate,
				pcId:businessCard.pcId,
				pcInsdate:businessCard.pcInsdate,
				pcProgramCode:businessCard.pcProgramCode,
				pcSpeech:businessCard.pcSpeech,
				pcStatus:businessCard.pcStatus,
				pcUptime:new Date(),
				userId:businessCard.userId,
				pcId:businessCard.pcId
			}).then((res)=>{
				console.log(res,"+++))))jjjjjjjjjjjj");
				wx.hideLoading()
			})
		}
		
	},
	canParseAsJson(jsonString) {
	    try {
	        JSON.parse(jsonString);
	        return true; // 如果没有抛出异常，说明可以被解析为JSON
	    } catch (e) {
	        return false; // 如果抛出异常，说明不是有效的JSON
	    }
	},
	getbct_id(){
		requestUtil.request("POST","/bcd_api/getbct_all",{
			bcId:this.data.bcId
		}).then((res)=>{
			if(res.data.status==200){
				this.canParseAsJson(res.data.data.bcFile)?res.data.data.bcFile=JSON.parse(res.data.data.bcFile):res.data.data.bcFile
				this.canParseAsJson(res.data.data.bcImgList)?res.data.data.bcImgList=JSON.parse(res.data.data.bcImgList):res.data.data.bcImgList
				this.canParseAsJson(res.data.data.pcSpeech)?res.data.data.pcSpeech=JSON.parse(res.data.data.pcSpeech):res.data.data.pcSpeech
				this.canParseAsJson(res.data.data.bcWxImg)?res.data.data.bcWxImg=JSON.parse(res.data.data.bcWxImg):res.data.data.bcWxImg
				this.canParseAsJson(res.data.data.bcUserImg)?res.data.data.bcUserImg=JSON.parse(res.data.data.bcUserImg):res.data.data.bcUserImg
				this.canParseAsJson(res.data.data.pcProgramCode)?res.data.data.pcProgramCode=JSON.parse(res.data.data.pcProgramCode):res.data.data.pcProgramCode
				let file=[]
				for (let i = 0; i < res.data.data.bcFile.length; i++) {
					file.push({
						name: res.data.data.bcFile[i].split("/").pop().split("_")[0]+"."+res.data.data.bcFile[i].split("/").pop().split(".")[1],
						url:res.data.data.bcFile[i]
					})
				}
				this.setData({
					bcd_info:res.data.data
				})
				this.setData({
					file_info:file
				})
				
			}
		})
	},
	input_data(e){
		setTimeout(()=>{
			let info=this.data.bcd_info
			if(e.currentTarget.dataset.type=='bcName'){
				info.bcName=e.detail.value
			}else if(e.currentTarget.dataset.type=='bcPosition'){
				info.bcPosition=e.detail.value
			}else if(e.currentTarget.dataset.type=='bcUserName'){
				info.bcUserName=e.detail.value
			}
			else if(e.currentTarget.dataset.type=='bcUserPhone'){
				info.bcUserPhone=e.detail.value
			}
			else if(e.currentTarget.dataset.type=='bcMailbox'){
				info.bcMailbox=e.detail.value
			}
			else if(e.currentTarget.dataset.type=='bcWxNumber'){
				info.bcWxNumber=e.detail.value
			}
			else if(e.currentTarget.dataset.type=='bcBriefIntroduction'){
				info.bcBriefIntroduction=e.detail.value
			}
			this.setData({
				bcd_info:info
			})
		},100)
	},
	get_bcAddress(){
		 wx.chooseLocation({
		   success: (res) => {
		     const { address, latitude, longitude } = res;
		     let info = this.data.bcd_info;
		     info.bcAddress = address;
		     info.bcXCoordinate = longitude;
		     info.bcYCoordinate = latitude;
		     this.setData({
		       bcd_info: info
		     });
		   },
		   fail: function(err) {
		     console.error('选择位置失败', err);
		   }
		 });

		  
	},
	DelImgid(e){
		console.log(e.currentTarget.dataset.type,'呃呃呃呃呃呃呃呃呃呃呃');
		let info=this.data.bcd_info
		for (var i = 0; i < info.bcImgList.length; i++) {
			if(info.bcImgList[i]==e.currentTarget.dataset.type){
				info.bcImgList.splice(i,1)
			}
		}
		this.setData({
			bcd_info:info
		})
	},
	chooseAndUploadFile: function(e) {
		let type=e.currentTarget.dataset.type
	    wx.chooseMessageFile({
	        count: 1, // 允许选择的文件个数
	        type: 'all', // 仍然设置为all，因为没有直接过滤特定文件类型的选项
	        success: (res) => {
	            const file = res.tempFiles[0];
	            const filePath = file.path;
	            const fileName = file.name;
				console.log(fileName,'fileName');
	            const fileExt = fileName.substring(fileName.lastIndexOf('.') + 1).toLowerCase(); // 获取并转换为小写文件扩展名
	            
	            // 检查文件类型
	            if (fileExt === 'pdf' || fileExt === 'docx') {
	                // 上传文件到服务器
	                this.uploadFileToServer(filePath, fileName,type);
	            } else {
	                wx.showToast({
	                    title: '仅支持PDF和DOCX文件',
	                    icon: 'none',
	                    duration: 2000
	                });
	            }
	        },
	        fail: (err) => {
	            console.error('选择文件失败', err);
	        }
	    });
	},
	
	uploadFileToServer: function(filePath, fileName,type) {
	    wx.uploadFile({
	        url: api.url + '/api/uploadfrie', // 服务器上传接口地址
	        filePath: filePath,
	        name: 'all',
	        formData: {
	            Name:fileName.split(".")[0]
	        },
	        success: (uploadRes) => {
	           const data = uploadRes.data;
	             let json = JSON.parse(data);
	             if(json.status == 200) {
	           				let info=this.data.bcd_info
							let a=json.data.http + json.data.path.split("uploadPath")[1].replace(/\\/g, "/")
	           				if(type=="bcFile"){
								if(info.bcFile==''){
									info.bcFile=[]
								}
	           					info.bcFile.push(a);
	           				}
							let file=this.data.file_info
							file.push({
								name:a.split("/").pop().split("_")[0]+"."+a.split("/").pop().split(".")[1],
								url:a
							})
	           				this.setData({
	           					bcd_info:info,
								file_info:file
	           				})
	             }
	        },
	        fail: (err) => {
	            console.error('上传失败', err);
	        }
	    });
	},
getwendang(e){
	if(e.target.dataset.id!="del"){
		wx.showLoading()
		let _this=this
		let path=e.target.dataset.type
		console.log(e,"eeeeeeeeeeeeeeeeeee");
		wx.downloadFile({
		  url: path,
		  success: function (res) {
		    wx.hideLoading();
		    const filePath = res.tempFilePath;
		    wx.openDocument({
		      filePath: filePath,
		      success: function (res) {
		        console.log('打开文档成功');
		      },
		      fail: function (err) {
		        console.error('打开文档失败', err);
		      }
		    });
		  },
		  fail: function (err) {
		    wx.hideLoading();
		    console.error('下载文件失败', err);
		  }
		});
	}else{
		let _this=this
		let path=e.target.dataset.type
		let info=this.data.bcd_info
		let file=this.data.file_info
		for (let i = 0; i < file.length; i++) {
			if(file[i].url==path){
				file.splice(i,1)
			}
		}
		for (let i = 0; i < info.bcFile.length; i++) {
			if(info.bcFile[i]==path){
				info.bcFile.splice(i,1)
			}
		}
		this.setData({
			file_info:file,
			bcd_info:info
		})
	}	

	},
	// 文件保存
	 uploadImageToServer(tempFilePath,type) {
	  wx.uploadFile({
	    url: api.url+"/api/upload", // 替换为你的服务器接口地址
	    filePath: tempFilePath,
	    name: 'image', // 服务器接收文件的字段名
	    success: (uploadRes) => {
	      const data = uploadRes.data;
	        let json = JSON.parse(data);
	        if(json.status == 200) {
				let info=this.data.bcd_info
				if(type=="bcWxImg"){
					info.bcWxImg=[json.data.http + json.data.path.split("uploadPath")[1].replace(/\\/g, "/")];
				}else if(type=="bcUserImg"){
					info.bcUserImg=[json.data.http + json.data.path.split("uploadPath")[1].replace(/\\/g, "/")];
				}else if(type=="bcImgList"){
					if(info.bcImgList==''){
						info.bcImgList=[]
					}
					info.bcImgList.push(json.data.http + json.data.path.split("uploadPath")[1].replace(/\\/g, "/"));
				}else if(type=="bcFile"){
					if(info.bcFile==''){
						info.bcFile=[]
					}
					info.bcFile.push(json.data.http + json.data.path.split("uploadPath")[1].replace(/\\/g, "/"));
				}
				this.setData({
					bcd_info:info
				})
	        }
	    },
	    fail: (err) => {
	      wx.showToast({
	        title: '上传失败',
	        icon: 'none',
	        duration: 2000
	      });
	      console.error('上传图片失败', err);
	    }
	  });
	},
	// 更新数据

	ChooseImage(e){
		console.log("被点击了哈哈哈，开心");
		let type=e.currentTarget.dataset.type
		wx.chooseImage({
			count: 1, //默认9
			sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
			sourceType: ['album'], //从相册选择
			success: (res) => {
				this.uploadImageToServer(res.tempFilePaths[0],type)
			}
		});
	},
	DelImg(){
		let info=this.data.bcd_info
		info.bcWxImg=[]
		this.setData({
			bcd_info:info
		})
	}
})